package com.ethan.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ethan.enums.BizCodeEnum;
import com.ethan.mapper.SysUserMapper;
import com.ethan.model.LoginUser;
import com.ethan.model.SysUserDO;
import com.ethan.req.LoginReq;
import com.ethan.service.SysUserService;
import com.ethan.util.JWTUtil;
import com.ethan.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Ethan
 * @since 2022-03-17
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDO> implements SysUserService {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public R login(LoginReq loginReq) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginReq.getUserName(),loginReq.getPwd());
        Authentication authentication =  authenticationManager.authenticate(authenticationToken);
        if (authentication!=null)
        {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String token = JWTUtil.geneJsonWebToken(loginUser);
            return R.buildSuccess(token);
        }

        return R.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
    }
}
